﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Personalization.VisitorGroups;
using System.Net;

namespace CriteriaPack.IPRangeCriterion
{
    [VisitorGroupCriterion(
        Category = "Technical Criteria",
        DisplayName = "IPRange",
        Description = "Criterion that matches certain IPv4 ranges")]
    public class IPRangeCriterion : CriterionBase<IPRangeModel>
    {
        public override bool IsMatch(System.Security.Principal.IPrincipal principal, System.Web.HttpContextBase httpContext)
        {
            if (httpContext.Request == null) return false;
            var addr = httpContext.Request["TestIP"] ?? httpContext.Request.UserHostAddress;
            
            if (Model.Condition == IPCompareCondition.Equal) return addr == Model.IP;

            var p1 = addr.Split('.').Select(s => int.Parse(s)).ToArray();
            var p2 = Model.IP.Split('.').Select(s => int.Parse(s)).ToArray();

            for (int i = 0; i < 4; i++)
            {
                if (p1[i] == p2[i]) continue;
                if((Model.Condition == IPCompareCondition.GT) && (p1[i]<p2[i]))    return false;
                if((Model.Condition == IPCompareCondition.LT) && (p1[i]>p2[i])) return false;
            }
            return true;

        }
    }
}
